<template>
  <div
    :class="`${prefixCls}-group-box`"
    v-if="filterGroup"
    :style="{ backgroundColor: getBackgroundColor(filterGroup) }"
  >
    <div :class="`${prefixCls}-group-operate`">
      <template v-for="subGroup in filterGroup.Groups" :key="subGroup">
        <SearchContainer :filterGroup="subGroup" :parentGroup="filterGroup" :columns="columns" />
      </template>
      <template v-for="rule in filterGroup.Rules" :key="rule">
        <ARow :class="`${prefixCls}-rule-box`">
          <Select
            size="small"
            v-model:value="rule.Field"
            :dropdownMatchSelectWidth="false"
            style="min-width: 150px"
            show-search
            :filterOption="handleFilterOption"
            :placeholder="t('component.adtable.search.selectColumn')"
            @change="handleRuleColumnsChange(rule)"
          >
            <SelectOption
              v-for="item in columns"
              :key="item.field"
              :value="item.field"
              :label="item.title"
            >
              {{ item.title }}
            </SelectOption>
          </Select>
          <Select
            size="small"
            style="min-width: 100px; margin-left: 5px"
            v-model:value="rule.Operate"
            :dropdownMatchSelectWidth="false"
            show-search
            :filter-option="handleFilterOption"
            :placeholder="t('component.adtable.search.selectOperate')"
          >
            <SelectOption
              v-for="entity in rule.column?.entities"
              :key="entity.Operate"
              :value="entity.Operate"
              :label="entity.Display"
            >
              {{ entity.Display }}
            </SelectOption>
          </Select>
          <div style="min-width: 200px; margin-left: 5px">
            <Tooltip :trigger="['hover']" placement="top">
              <template v-if="rule.Value" #title>
                <span>
                  {{ rule.Value }}
                </span>
              </template>
              <!-- 固定枚举 -->
              <template v-if="rule.column?.formRender?.name === 'Select'">
                <Select
                  v-model:value="rule.Value"
                  :dropdownMatchSelectWidth="false"
                  show-search
                  :filterOption="handleFilterOption"
                  :placeholder="t('component.adtable.search.selectValue')"
                  size="small"
                  style="width: 100%; min-width: 100%"
                >
                  <SelectOption
                    v-for="item in rule.column?.enumData"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                  >
                    {{ item.label }}
                  </SelectOption>
                </Select>
              </template>
              <!-- 远程下拉 -->
              <template v-if="rule.column?.formRender?.name === 'ApiSelect'">
                <ApiSelect
                  v-model:value="rule.Value"
                  :dropdownMatchSelectWidth="false"
                  :placeholder="t('component.adtable.search.selectValue')"
                  :api="rule.column?.formRender?.props?.api"
                  :params="rule.column?.formRender?.props?.params"
                  :immediate="rule.column?.formRender?.props?.immediate"
                  :resultField="rule.column?.formRender?.props?.resultField"
                  :labelField="rule.column?.formRender?.props?.labelField"
                  :valueField="rule.column?.formRender?.props?.valueField"
                  :allowClear="rule.column?.formRender?.props?.allowClear"
                  :showSearch="rule.column?.formRender?.props?.showSearch"
                  :optionFilterProp="rule.column?.formRender?.props?.optionFilterProp"
                  size="small"
                  style="width: 100%; min-width: 100%"
                />
              </template>
              <!-- 远程下拉树 -->
              <template v-if="rule.column?.formRender?.name === 'ApiTreeSelect'">
                <ApiTreeSelect
                  v-model:value="rule.Value"
                  :dropdownMatchSelectWidth="false"
                  :placeholder="t('component.adtable.search.selectValue')"
                  :api="rule.column?.formRender?.props?.api"
                  :params="rule.column?.formRender?.props?.params"
                  :immediate="rule.column?.formRender?.props?.immediate"
                  :resultField="rule.column?.formRender?.props?.resultField"
                  :labelField="rule.column?.formRender?.props?.labelField"
                  :valueField="rule.column?.formRender?.props?.valueField"
                  :childrenField="rule.column?.formRender?.props?.childrenField"
                  :allowClear="rule.column?.formRender?.props?.allowClear"
                  :showSearch="rule.column?.formRender?.props?.showSearch"
                  :treeNodeFilterProp="rule.column?.formRender?.props?.treeNodeFilterProp"
                  :treeDefaultExpandAll="rule.column?.formRender?.props?.treeDefaultExpandAll"
                  size="small"
                  style="width: 100%; min-width: 100%"
                />
              </template>
              <!-- 数值类型 -->
              <template v-if="['InputNumber'].includes(rule.column?.formRender?.name)">
                <InputNumber
                  v-model:value="rule.Value"
                  :precision="rule.column?.formRender?.props?.precision"
                  :placeholder="t('component.adtable.search.inputNumber')"
                  size="small"
                  style="width: 100%; min-width: 100%"
                />
              </template>
              <!-- 整数/字符类型 -->
              <template v-if="[undefined, null, 'Input'].includes(rule.column?.formRender?.name)">
                <Input
                  v-model:value="rule.Value"
                  :placeholder="
                    rule.column?.dataType === 'integer'
                      ? t('component.adtable.search.inputInteger')
                      : t('component.adtable.search.inputString')
                  "
                  size="small"
                  style="width: 100%; min-width: 100%"
                  :onkeyup="
                    rule.column?.dataType === 'integer'
                      ? 'value=value.replace(/[^{1,2,3,4,5,6,7,8,9,0}]/g,\'\')'
                      : 'value=value'
                  "
                />
              </template>
              <!-- 密码字符类型 -->
              <template v-if="['InputPassword'].includes(rule.column?.formRender?.name)">
                <InputPassword
                  v-model:value="rule.Value"
                  :placeholder="t('component.adtable.search.inputString')"
                  size="small"
                  style="width: 100%; min-width: 100%"
                />
              </template>
              <!-- 布尔类型 -->
              <template v-if="rule.column?.formRender?.name === 'Switch'">
                <Switch v-model:checked="rule.Value" size="small" />
              </template>
              <!-- 日期时间/日期 -->
              <template v-if="['DatePicker'].includes(rule.column?.formRender?.name)">
                <DatePicker
                  v-model:value="rule.Value"
                  :showTime="rule.column?.formRender?.props?.showTime"
                  :placeholder="
                    rule.column?.formRender?.props?.showTime
                      ? t('component.adtable.search.selectDateTime')
                      : t('component.adtable.search.selectDate')
                  "
                  size="small"
                  style="width: 100%; min-width: 100%"
                />
              </template>
              <!-- 时间 -->
              <template v-if="rule.column?.formRender?.name === 'TimePicker'">
                <TimePicker
                  v-model:value="rule.Value"
                  :placeholder="t('component.adtable.search.selectTime')"
                  size="small"
                  style="width: 100%; min-width: 100%"
                />
              </template>
            </Tooltip>
          </div>
          <Tooltip :title="t('component.adtable.search.removeRule')" placement="top">
            <Button
              size="small"
              style="margin-left: 5px"
              shape="circle"
              @click="handleRemoveRule(rule, filterGroup)"
            >
              <Icon icon="ant-design:close-outlined" />
            </Button>
          </Tooltip>
        </ARow>
      </template>

      <Select
        :value="filterGroup.Operate"
        size="small"
        :dropdownMatchSelectWidth="false"
        @change="(value) => changeGroupOperate(value, filterGroup)"
      >
        <SelectOption
          v-for="entity in groupOperateEntities"
          :key="entity.Operate"
          :value="entity.Operate"
          :label="entity.Display"
        >
          {{ entity.Display }}
        </SelectOption>
      </Select>
      <Button size="small" style="margin-left: 5px" @click="handleAddGroup(filterGroup)">
        <Icon icon="bx:bx-add-to-queue" />{{ t('component.adtable.search.addGroup') }}
      </Button>
      <Button size="small" style="margin-left: 5px" @click="handleAddRule(filterGroup)">
        <Icon icon="ic-outline-rule" />{{ t('component.adtable.search.addRule') }}
      </Button>
      <Button
        size="small"
        style="margin-left: 5px"
        v-if="filterGroup.Level > 1"
        @click="handleRemoveGroup(filterGroup, parentGroup)"
      >
        <Icon icon="subway:remove-playlist" />{{ t('component.adtable.search.removeGroup') }}
      </Button>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import type { PropType } from 'vue';
  import { ref } from 'vue';
  import { useDesign } from '@/hooks/web/useDesign';
  import { useRootSetting } from '@/hooks/setting/useRootSetting';
  import {
    Row,
    Button,
    Select,
    InputNumber,
    Input,
    Switch,
    DatePicker,
    TimePicker,
    Tooltip,
  } from 'ant-design-vue';
  import Icon from '@/components/Icon/Icon.vue';
  import { ApiSelect, ApiTreeSelect } from '@/components/Form';

  import { useI18n } from '@/hooks/web/useI18n';

  import { FilterRule, FilterGroup } from '#/request';
  import { FilterOperateEnum, FilterOperateEntity } from '@/enums/filterOperateEnum';
  import { changeFilterRuleType } from '../hooks';
  import { AdColumn } from '../types/table';

  const ARow = Row;
  const SelectOption = Select.Option;
  const InputPassword = Input.Password;

  defineOptions({ name: 'SearchContainer' });
  const props = defineProps({
    /** 查询条件组 */
    filterGroup: {
      type: Object as PropType<FilterGroup>,
      default: null,
    },
    /** 父级查询条件组 */
    parentGroup: {
      type: Object as PropType<FilterGroup>,
      default: null,
    },
    /** 列配置 */
    columns: {
      type: [Array] as PropType<AdColumn[]>,
      default: () => [],
    },
  });

  const { t } = useI18n();
  const { getDarkMode } = useRootSetting();
  const { prefixCls } = useDesign('basic-table-search-container');

  const groupOperateEntities = ref<FilterOperateEntity[]>([
    new FilterOperateEntity(FilterOperateEnum.And),
    new FilterOperateEntity(FilterOperateEnum.Or),
  ]);

  /** 获取背景色 */
  function getBackgroundColor(filterGroup: FilterGroup) {
    if (getDarkMode.value === 'dark') {
      return filterGroup.Level % 2 == 0 ? '#151515' : '#1e1e1e';
    } else {
      return filterGroup.Level % 2 == 0 ? '#eee' : '#fff';
    }
  }

  /** 组筛选条件值更改 */
  function changeGroupOperate(value: any, group: FilterGroup) {
    group.Operate = value;
  }

  /** 处理条件-列选择 */
  function handleRuleColumnsChange(rule: FilterRule) {
    // console.log(rule);
    if (!rule) {
      return;
    }
    rule.column = props.columns.find((n) => n.field === rule.Field) as AdColumn;
    if (!rule.column) {
      return;
    }
    changeFilterRuleType(rule, rule.column);
  }
  /** 处理选择框筛选 */
  const handleFilterOption = (input: string, option: any) => {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  /** 处理增加分组 */
  function handleAddGroup(group: FilterGroup) {
    const subGroup = new FilterGroup();
    subGroup.Level = group.Level + 1;
    group.Groups.push(subGroup);
  }
  /** 处理删除分组 */
  function handleRemoveGroup(group: FilterGroup, parentGroup: FilterGroup) {
    if (parentGroup) {
      const index = parentGroup.Groups.indexOf(group);
      if (index >= 0) {
        parentGroup.Groups.splice(index, 1);
      }
    }
  }

  /** 处理增加条件 */
  function handleAddRule(group: FilterGroup) {
    const rule = new FilterRule(undefined, null);
    if (props.columns?.length > 0) {
      rule.Field = props.columns[0].field;
      rule.column = props.columns.find((n) => n.field === rule.Field) as AdColumn;
      // console.log('rule.column', rule.column);
      if (!rule.column) {
        return;
      }
      changeFilterRuleType(rule, rule.column);
    }
    group.Rules.push(rule);
  }
  /** 处理删除条件 */
  function handleRemoveRule(rule: FilterRule, group: FilterGroup) {
    // console.log('rule', rule);
    // console.log('group', group);
    if (rule) {
      const index = group.Rules.indexOf(rule);
      if (index >= 0) {
        group.Rules.splice(index, 1);
      }
    }
  }
</script>

<style lang="less">
  @prefix-cls: ~'@{namespace}-basic-table-search-container';

  .@{prefix-cls} {
    &-group-box {
      margin: 2px;
      padding: 3px;
      border: dashed 2px #ddd;
    }

    &-group-operate {
      margin: 3px 0;
    }

    &-rule-box {
      margin: 3px;
    }
  }

  [data-theme='dark'] {
    .@{prefix-cls} {
      &-group-box {
        border: dashed 2px #303030;
      }
    }
  }
</style>
